from main import basedir
from flask import request
import time, os
from main.code import *
# import numpy as np
from main.utils import InterfaceHelper, RequestHelper, FileHelper, ImageHelper, EmailHelper
from main.dbs.result_db import *
from flask_restplus import Api, Resource, fields
from . import api
import json
import time
# 定义命名空间
ns = api.namespace('result', description='Result api')

need_model = api.model('NeedModel', {
    'x': fields.String(description='横坐标'),
    'y': fields.Integer(description='纵坐标'),
})

result_model = api.model('ResultModel', {
    'user_id': fields.Integer(description='用户id'),
    'mean': fields.Float(description='均值'),
    'variance': fields.Float(description='方差'),
    'cost': fields.Float(description='成本'),
    'price': fields.Float(description='售价'),
    'repurchase': fields.Float(description='回购价格'),
    'profit': fields.Float(description='利润=卖出数量*5-订购数量*3+剩余数量*2'),
    'need': fields.List(fields.Nested(need_model), description='需求'),
    'data': fields.List(fields.Float(), description='需求原始数据'),
    'day': fields.List(fields.Integer(), description='天数'),
    'buy': fields.Integer(description='购买数量'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态'),
    'count': fields.Integer(description='游戏次数')
})

post_result_model = api.model("PostResultModel", {
    'user_id': fields.Integer(description='用户id'),
    'mean': fields.Float(description='均值'),
    'variance': fields.Float(description='方差'),
    'cost': fields.Float(description='成本'),
    'price': fields.Float(description='售价'),
    'repurchase': fields.Float(description='回购价格'),
    'profit': fields.Float(description='利润=卖出数量*5-订购数量*3+剩余数量*2'),
    'game': fields.Integer(description='游戏id 1 or 2'),
    'need': fields.Float(description='需求'),
    'buy': fields.Integer(description='购买数量'),
})

data_model = api.model('DataModel', {
    'cost': fields.Float(description='成本'),
    'price1': fields.Float(description='旺季售价'),
    'price2': fields.Float(description='淡季售价'),
    'repurchase': fields.Float(description='回购价格'),
    'mean1': fields.Float(description='旺季均值'),
    'variance1': fields.Float(description='旺季方差'),
    'mean2': fields.Float(description='淡季均值'),
    'variance2': fields.Float(description='淡季方差')
})


result_list_model = api.model('ResultListModel', {
    'result_list': fields.List(fields.Nested(post_result_model)),
    'total': fields.Integer(description='数量'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态')
})


@ns.route('/<int:user_id>')
class ResultApi(Resource):
    '''数据获取接口'''

    @ns.doc("get_result_")
    @ns.marshal_with(result_model)
    @ns.param("game", "游戏id")
    def get(self, user_id):
        '''获取数据'''
        responses = {}
        # 统计游戏次数
        parameters = RequestHelper.formToDict(request)
        count = count_by_user_id_and_game_id(user_id=user_id, game_id=parameters['game'])
        responses['count'] = count
        if count > 3:
            return success(responses, message="游戏次数上限", status=False)
        # 获取游戏参数
        fp = open('./data.json', 'r', encoding='UTF-8')
        dic = json.load(fp)
        if parameters['game'] == '1':
            mean = dic['mean1']
            variance = dic['variance1']
            game = dic['game1']
            responses['price'] = dic['price1']
        elif parameters['game'] == '2':
            mean = dic['mean2']
            variance = dic['variance2']
            game = dic['game2']
            responses['price'] = dic['price2']
        need = []
        num = 0
        while num < 3:
            # d = int(np.random.normal(mean, variance ** .5))
            # if 290 >= d >= 100:

            # need.append(d)
            num += 1
        day = []
        # for i in range(len(need)):
        #     day[(need[i] - 90) // 20] += 1
        for i in game:
            day.append(i['y'])
        # responses['mean'] = round(np.mean(need), 2)
        # responses['variance'] = round(np.var(need), 2)
        responses['mean'] = mean
        responses['variance'] = variance
        responses['data'] = need
        # need_dic = []
        # need = sorted(need)
        # while need:
        #     dict = {}
        #     dict['day'] = need.count(need[0])
        #     dict['need'] = need[0]
        #     for i in range(dict['day']):
        #         need.remove(dict['need'])
        #     need_dic.append(dict)
        responses['need'] = game
        responses['day'] = day
        return success(responses)

    @ns.doc("post_data")
    @ns.expect(post_result_model)
    def post(self, user_id):
        '''上传结果'''
        fp = open('./data.json', 'r', encoding='UTF-8')
        dic = json.load(fp)
        parameters = RequestHelper.formToDict(request)
        # 下单数量大于需求
        if int(parameters['buy']) > int(parameters['need']):
            parameters['profit'] = int(parameters['need']) * parameters['price'] - int(parameters['buy']) * dic['cost'] + (
                    int(parameters['buy']) - int(parameters['need'])) * dic['repurchase']
        else:
            parameters['profit'] = int(parameters['buy']) * parameters['price'] - int(parameters['buy']) * dic['cost']
        parameters['need'] = str(parameters['need'])
        result = JSONHelper.dictToObj(parameters, Result)
        if insert(result):
            return success()
        return fail(message='上传失败')


    @ns.doc("delete_result")
    def delete(self, user_id):
        '''删除某人游戏结果'''
        result_list = query_by_user_id(user_id)
        if result_list:
            delete(result_list)
            return success()
        else:
            return success(message='result_list is empty', status=False)
        return fail()

@ns.route('/data')
class ResultDataApi(Resource):
    '''游戏参数'''
    @ns.doc("get_data")
    @ns.marshal_with(data_model)
    def get(self):
        '''获取游戏参数'''
        fp = open('./data.json', 'r', encoding='UTF-8')
        dic = json.load(fp)
        return success(dic)


    @ns.doc("put_data")
    @ns.expect(data_model)
    def put(self):
        '''修改参数'''
        parameters = RequestHelper.formToDict(request)
        fp = open('./data.json', 'r', encoding='UTF-8')
        dic = json.load(fp)
        for key in parameters:
            dic[key] = float(parameters[key])
        fp.close()
        fp = open('./data.json', 'w')
        json.dump(dic, fp)
        return success()


@ns.route('/email/<string:email>')
class EmailApi(Resource):
    '''邮件api'''
    @ns.doc("get_email")
    def get(self, email):
        today = time.strftime('%Y-%m-%d', time.localtime())
        filename = today + ".csv"
        path = os.path.join("./main/static", filename)
        fp = open(path, "w", encoding='utf-8-sig')
        fp.write("%s,%s,%s,%s,%s,%s,%s,%s,%s\n" % ("成本", "售价", "回购价格", "利润", "购买数量", "需求", "均值", "方差", "用户"))
        for line in query():
            fp.write("%s,%s,%s,%s,%s,%s,%s,%s,%s\n" % (line.cost, line.price, line.repurchase, line.profit, line.buy,
                                                    line.need.replace(',', ';'), line.mean, line.variance, line.user_id))
        fp.close()
        if EmailHelper.send_email_file(email, path):
            return success()
        return fail()


@ns.route('/list/<int:user_id>')
class ResultListApi(Resource):
    '''result list api'''

    @ns.doc("get_result_list")
    @ns.marshal_with(result_list_model)
    def get(self, user_id):
        '''获取结果列表'''
        responses = {}
        result_list = []
        for i in query_by_user_id(user_id):
            result = i.to_json()
            result['day'] = None
            result_list.append(result)
        responses['result_list'] = result_list
        responses['total'] = len(result_list)
        return success(responses)



